﻿using Abp.Domain.Entities;
using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input.DeathModelsinput;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Dto.Output.DeathModelsOutPut;
using IntelligentAgriculture.Contracts.Dto.Output.EarTagOutput;
using IntelligentAgriculture.Contracts.Dto.Output.PageOutput;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Impl;
using IntelligentAgriculture.Domain.Impl.SheepFileModellmpl;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Interface.IEarTagReposiotry;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using Microsoft.Extensions.Logging;
using Org.BouncyCastle.Crypto;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Metadata.Edm;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace IntelligentAgriculture.Services
{
    public class DeathModelService:iDeathModelService
    {
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IridegRepository _iridegRepository;
        /// <summary>
        /// 栏位仓储
        /// </summary>
        private readonly IColumnManRepository _columnManRepository;

        /// <summary>
        /// 耳号仓储
        /// </summary>
        private readonly IEarTagReposiotry _earTagReposiotry;
        /// <summary>
        /// 羊只档案仓储
        /// </summary>
        private readonly ISheepAblactationRepository _sheepFileModelRepository;

        private readonly ISheepFileModelRepository _ISheepFileModelRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SheepAblactationService> _logger;

        private readonly iDeathModelRepository _deathModelRepository;


        public DeathModelService(IMapper mapper, IridegRepository iridegRepository, IColumnManRepository columnManRepository, IEarTagReposiotry earTagReposiotry, ILogger<SheepAblactationService> logger, ISheepAblactationRepository sheepFileModelRepository, iDeathModelRepository deathModelRepository, ISheepFileModelRepository iSheepFileModelRepository)
        {
            _mapper = mapper;
            _iridegRepository = iridegRepository;
            _columnManRepository = columnManRepository;
            _earTagReposiotry = earTagReposiotry;
            _logger = logger;
            _sheepFileModelRepository = sheepFileModelRepository;
            _deathModelRepository = deathModelRepository;
            _ISheepFileModelRepository = iSheepFileModelRepository;
        }



        public async Task<List<Sheepfilemodel>> GetBuildByEar(string earTagNumber)
        {
            try
            {
                //获取所有羊只档案表数据
                var sheepfile = await _sheepFileModelRepository.GetEweEarTagsFromSheepFile();
                sheepfile = sheepfile.Where(p => p.EarTag == earTagNumber).ToList();
                return sheepfile;
            }
            catch (Exception ex)
            {
                _logger.LogError("！" + ex.Message);
                throw;
            }
        }

        public async Task<List<Eartag>> GetEarShowinfo()
        {
            var sheepfile = await _sheepFileModelRepository.GetEweEarTagsFromSheepFile();
            sheepfile = sheepfile.Where(x => x.PresentState == 1).ToList();
            // 创建一个 string 类型的 list 集合用来存储查询到的耳号
            List<string> earTags = sheepfile.Select(s => s.EarTag).ToList();
            //获取所有耳号的信息
            var earTagDetails = await _earTagReposiotry.GetShow();
            // 过滤掉已经删除的耳号
            earTagDetails = earTagDetails.Where(e => e.Isdel == false);
            // 根据 earTags 里的耳号，去耳号表获取对应耳号信息
            var matchingEarTags = earTagDetails.Where(e => earTags.Contains(e.EarTagNumber)).ToList();


            return matchingEarTags;
        }




        /// <summary>
        /// 根据指定条件获取显示或查询功能的结果集合
        /// </summary>
        /// <param name="input">查询条件的输入参数</param>
        /// <returns>包含分页结果的异步任务，返回显示或查询功能的结果集合</returns>
        public async Task<PagesOutput<DeathModelsOutPut>>GetShow(DeathModelInput input)
        {
            try
            {
               
                var list = await _deathModelRepository.GetShow();
                if (!string.IsNullOrEmpty(input.EarTag))
                {
                    list = list.Where(x =>x.EarTag.Contains(input.EarTag));
                }
                if (input.DeathType > 0)
                {
                    list = list.Where(x => x.DeathType == input.DeathType);
                }
             


                var result = new PagesOutput<DeathModelsOutPut>()
                {
                    Total = list.Count(),
                    PageSize = input.PageSize
                };



                var query = list.OrderByDescending(x => x.DeathId).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize);
                result.Data = _mapper.Map<List<DeathModelsOutPut>>(query);
                return result;
            }
            catch (Exception)
            {

                throw;
            }


        }

        /// <summary>
        /// 异步删除特定 ID 对应的记录
        /// </summary>
        /// <param name="id">要删除记录的唯一标识符</param>
        /// <returns>
        /// 表示受影响的记录数的整数值（成功删除时返回 1）。
        /// </returns>
        public async Task<int> Delete(int id)
        {
            try
            {
                return await _deathModelRepository.Delete(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        
        /// <summary>
        /// 异步更新指定实体的数据
        /// </summary>
        /// <param name="entity">要更新的实体对象</param>
        /// <returns>
        /// 表示受影响的记录数的整数值（成功更新时返回 true）
        /// </returns>
        /// <exception cref="NotImplementedException">如果方法未实现，则抛出此异常</exception>
        public async Task<int> UpateEartag(Deathmodel entity)
        {
            try
            {
                var list = _mapper.Map<Deathmodel>(entity);
                return await _deathModelRepository.UpdateAsync(list);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 根据给定的 ID 异步查找并映射死亡模型
        /// </summary>
        /// <param name="id">要查找的记录的唯一标识符</param>
        /// <returns>
        /// 包含查找到的死亡模型的输出对象，如果未找到则返回 null
        /// </returns>
        /// <exception cref="Exception">查找过程中出现的任何异常均会被抛出</exception>
        public async Task<DeathModelsOutPut> Find(int id)
        {
            try
            {
                var list = await _deathModelRepository.Find(id);
                if (list == null)
                {
                    return null;
                }
                var lists = _mapper.Map<DeathModelsOutPut>(list);
                return lists;
            }
            catch (Exception)
            {

                throw;
            }
        }





        public async Task<int> Add(List<Deathmodel> add)
        {
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 异步执行数据库操作
                    int result = await _deathModelRepository.Add(add); // 直接传入 add，不需要再映射

                    // 更新 SheepFileModel 的 PresentState
                    var list = await _ISheepFileModelRepository.GetSheepfilemodels();
                    var sheepFileModels = new List<Sheepfilemodel>();
                    foreach (var entity in add)
                    {
                        var sheepFileModel = list.FirstOrDefault(x => x.EarTag == entity.EarTag);
                        if (sheepFileModel != null)
                        {
                            sheepFileModel.PresentState = 4;
                        }
                        sheepFileModels.Add(sheepFileModel);
                    }

                    await _ISheepFileModelRepository.UpdateListSheepFileModel(sheepFileModels); // 传入更新后的 list

                    // 提交事务
                    transaction.Complete();

                    return result; // 返回操作的结果，可能是影响的行数或者其他返回值
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    Console.WriteLine("事务回滚: " + ex.Message);
                    throw; // 抛出异常或返回错误状态码，让调用者处理
                }
            }
        }
        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <param name="hrids"></param>
        /// <returns></returns>
        public async Task<int> DeleteRange(IEnumerable<int> ids)
        {
            try
            {
                return await _deathModelRepository.DeleteRange(ids);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
